import 'package:flutter/material.dart';
import 'package:flutter_pagewise/flutter_pagewise.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:loxen/api/http_server/user_info.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/inspiration/inspiration_info_bean.dart';
import 'package:loxen/mode/mine/user_info_edit.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/view/inspiration/inspiration_item_widget.dart';
import 'package:loxen/view/master/master_index_item.dart';
import 'package:loxen/view/mine/user_dynamic_widget.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:loxen/viewmode/mine_user_info_viewmodel.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';

class _Title extends SliverPersistentHeaderDelegate {
  Widget numShow(String number, String text) {
    return Column(
      children: <Widget>[
        Text(
          number,
          style: TextStyle(
            color: Colors.white,
            fontSize: 32.sp,
          ),
        ),
        Text(
          text,
          style: TextStyle(
            color: Colors.white,
            fontSize: 24.sp,
          ),
        )
      ],
    );
  }

  Widget textButton(String text, Color textColor, Color bgColor, Function() onClick) {
    return SizedBox(
      width: 170.w,
      height: 48.h,
      child: FlatButton(
        onPressed: onClick,
        child: Text(
          text,
          style: TextStyle(fontSize: 24.sp, color: textColor),
        ),
        color: bgColor,
      ),
    );
  }

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Stack(
      children: <Widget>[
        Builder(builder: (BuildContext context) {
          String path =
              context.select<MineUserInfoViewModel, String>((value) => value.user.user.background);
          return CachedNetworkImage(
            imageUrl: ImageUrlUtil.getClean(path),
            width: double.infinity,
            height: 480.h,
            fit: BoxFit.cover,
          );
        }),
        Container(
          alignment: Alignment.topCenter,
          margin: EdgeInsets.only(top: 30.h),
          child: Row(
            children: <Widget>[
              MySubassembly.getBackIcon(context),
              Expanded(child: Constants.empty),
              MySubassembly.getSearchIcon(null, text: Constants.empty, width: 44.w, height: 8.w)
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 65.h),
          alignment: Alignment.topCenter,
          child: Column(
            children: <Widget>[
              ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(160.w)),
                child: Builder(
                  builder: (BuildContext context) {
                    String path = context
                        .select<MineUserInfoViewModel, String>((value) => value.user.user.portrait);
                    return CachedNetworkImage(
                      imageUrl: ImageUrlUtil.getClean(path, w: 160),
                      width: 160.w,
                      height: 160.w,
                      fit: BoxFit.cover,
                    );
                  },
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 10.h),
                child: Builder(
                  builder: (BuildContext context) {
                    String name = context
                        .select<MineUserInfoViewModel, String>((value) => value.user.user.nickname);
                    return Text(
                      name,
                      style: TextStyle(
                          fontSize: 30.sp, color: Theme.of(context).textTheme.subtitle1.color),
                    );
                  },
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 20.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Builder(builder: (context) {
                      String str;
                      int like = context
                          .select<MineUserInfoViewModel, int>((value) => value.user.is_likes);
                      if (like == 0) {
                        str = StringResources.dian_zan;
                      } else {
                        str = StringResources.yi_dian_zan;
                      }
                      return textButton(str, Theme.of(context).textTheme.subtitle2.color,
                          Theme.of(context).backgroundColor, () {
                        if (context.read<LoginViewModel>().isLogin()) {
                          Navigator.of(context).pushNamed(Routes.login_page);
                          return;
                        }
                        context
                            .read<MineUserInfoViewModel>()
                            .thisUserLike((msg) => Toast.show(msg, context));
                      });
                    }),
                    Container(
                      width: 30.w,
                      child: Constants.empty,
                    ),
                    Builder(
                      builder: (BuildContext context) {
                        int follower = context
                            .select<MineUserInfoViewModel, int>((value) => value.user.is_follow);
                        String str;
                        if (follower == 0) {
                          str = StringResources.guan_zhu;
                        } else {
                          str = StringResources.yi_guan_zhu;
                        }
                        return textButton(str, Theme.of(context).textTheme.subtitle1.color,
                            Theme.of(context).primaryColor, () {
                          if (context.read<LoginViewModel>().isLogin()) {
                            Navigator.of(context).pushNamed(Routes.login_page);
                            return;
                          }
                          if (follower == 0) {
                            context.read<MineUserInfoViewModel>().follower();
                          } else {
                            context.read<MineUserInfoViewModel>().unFollower();
                          }
                        });
                      },
                    ),
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 30.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    Builder(
                      builder: (BuildContext context) {
                        String like = context.select<MineUserInfoViewModel, String>(
                            (value) => value.user.like_num.toString());
                        return numShow(like, StringResources.huo_zan);
                      },
                    ),
                    Builder(
                      builder: (BuildContext context) {
                        String follow = context.select<MineUserInfoViewModel, String>(
                            (value) => value.user.follow_num.toString());
                        return numShow(follow, StringResources.ren_qi);
                      },
                    ),
                    Builder(
                      builder: (BuildContext context) {
                        String comment = context.select<MineUserInfoViewModel, String>(
                            (value) => value.user.comment_num.toString());
                        return numShow(comment, StringResources.ping_lun);
                      },
                    ),
                  ],
                ),
              )
            ],
          ),
        )
      ],
    );
  }

  @override
  double get maxExtent => 472.h;

  @override
  double get minExtent => 472.h;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}

class _TabBar extends SliverPersistentHeaderDelegate {
  final ValueNotifier select;

  _TabBar(this.select);

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          tabBar(StringResources.zuo_pin, 0),
          tabBar(StringResources.da_shi_zhuo, 1),
          tabBar(StringResources.zi_liao, 2),
          tabBar(StringResources.dong_tai, 3),
        ],
      ),
    );
  }

  @override
  double get maxExtent => 110.h;

  @override
  double get minExtent => 110.h;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }

  Widget tabBar(String text, int index) {
    return Builder(builder: (context) {
      bool select = context.watch<int>() == index;
      return GestureDetector(
        onTap: () {
          this.select.value = index;
        },
        child: Padding(
          padding: EdgeInsets.only(top: 36.h, bottom: 29.h),
          child: Text(
            text,
            style: TextStyle(
                fontSize: 32.sp,
                fontWeight: select ? FontWeight.bold : FontWeight.normal,
                color: select ? Colors.black : Color(0xFF666666)),
          ),
        ),
      );
    });
  }
}

class MineUserInfoWidget extends StatelessWidget {
  final ValueNotifier<int> select = ValueNotifier(0);
  final String userId;

  MineUserInfoWidget({Key key, this.userId}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) {
        MineUserInfoViewModel viewModel = MineUserInfoViewModel();
        viewModel.loadData(userId);
        return viewModel;
      },
      builder: (context, _) {
        return Scaffold(
          extendBodyBehindAppBar: true,
          backgroundColor: Theme.of(context).backgroundColor,
          body: Builder(builder: (context) {
            BaseState state =
                context.select<MineUserInfoViewModel, BaseState>((value) => value.mState);
            if (state == BaseState.LOADING) {
              return LoadingWidget();
            }
            if (state == BaseState.EMPTY) {
              return EmptyWidget();
            }
            if (state == BaseState.FAIL) {
              return FailWidget(onClick: () {
                context.read<MineUserInfoViewModel>().loadData(userId);
              });
            }
            var fileShow = Provider.of<MineUserInfoViewModel>(context, listen: false).fileShow;
            return MediaQuery.removePadding(
              context: context,
              removeTop: true,
              child: ValueListenableProvider.value(
                value: select,
                builder: (context, _) {
                  return NestedScrollView(
                    body: Stack(
                      children: <Widget>[
                        Offstage(
                          child: const _InspirationList(),
                          offstage: context.watch<int>() != 0,
                        ),
                        Offstage(
                          child: MasterFileList(
                            data: fileShow,
                            isMe: false,
                            userId: userId,
                          ),
                          offstage: context.watch<int>() != 1,
                        ),
                        Offstage(
                          child: const _UserData(),
                          offstage: context.watch<int>() != 2,
                        ),
                        Offstage(
                          child: const UserDynamicWidget(),
                          offstage: context.watch<int>() != 3,
                        ),
                      ],
                    ),
                    headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
                      return [
                        SliverPersistentHeader(
                          delegate: _Title(),
                        ),
                        SliverPersistentHeader(
                          delegate: _TabBar(select),
                          pinned: true,
                          floating: true,
                        ),
                      ];
                    },
                  );
                },
              ),
            );
          }),
        );
      },
    );
  }

  Widget tabBar(String text, int index) {
    return Builder(builder: (context) {
      bool select = context.watch<int>() == index;
      return GestureDetector(
        onTap: () {
          this.select.value = index;
        },
        child: Padding(
          padding: EdgeInsets.only(top: 36.h, bottom: 29.h),
          child: Text(
            text,
            style: TextStyle(
                fontSize: 32.sp,
                fontWeight: select ? FontWeight.bold : FontWeight.normal,
                color: select ? Colors.black : Color(0xFF999999)),
          ),
        ),
      );
    });
  }

  Widget numShow(String number, String text) {
    return Column(
      children: <Widget>[
        Text(
          number,
          style: TextStyle(
            color: Colors.white,
            fontSize: 28.sp,
          ),
        ),
        Text(
          text,
          style: TextStyle(
            color: Colors.white.withAlpha(153),
            fontSize: 22.sp,
          ),
        )
      ],
    );
  }

  Widget textButton(String text, Color textColor, Color bgColor, Function() onClick) {
    return SizedBox(
      width: 170.w,
      height: 48.h,
      child: FlatButton(
        onPressed: onClick,
        child: Text(
          text,
          style: TextStyle(fontSize: 24.sp, color: textColor),
        ),
        color: bgColor,
      ),
    );
  }
}

class _InspirationList extends StatelessWidget {
  const _InspirationList();

  @override
  Widget build(BuildContext context) {
    PagewiseLoadController<InspirationInfo> pageLoadController = PagewiseLoadController(
        pageFuture: (page) {
          return context.read<MineUserInfoViewModel>().nextInspiration(page);
        },
        pageSize: Provider.of<MineUserInfoViewModel>(context, listen: false).pageSize);
    return Padding(
      padding: EdgeInsets.only(left: 36.w),
      child: PagewiseListView<InspirationInfo>(
        loadingBuilder: (_) => MySubassembly.getLoadingItem(),
        noItemsFoundBuilder: (_) => MySubassembly.getNullItem(msg: '没有更多内容'),
        addAutomaticKeepAlives: false,
        itemBuilder: (_, entity, index) {
          return ItemWidget(
            entity: entity,
            isMy: true,
          );
        },
        pageLoadController: pageLoadController,
      ),
    );
  }
}

//用户资料
class _UserData extends StatelessWidget with UserInfoMixin {
  const _UserData({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ValueNotifier<UserInfoEdit> data = ValueNotifier(null);
    String userId = Provider.of<MineUserInfoViewModel>(context, listen: false).user.id.toString();
    userData(userId: userId).listen((event) {
      if (event != null) {
        data.value = event;
      }
    });
    return ValueListenableProvider<UserInfoEdit>.value(
      value: data,
      builder: (context, _) {
        var data = context.watch<UserInfoEdit>();
        if (data != null) {
          return ListView(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 40.h, left: 37.w),
                child: Text(
                  StringResources.ji_ben_zi_liao,
                  style: TextStyle(
                      fontSize: 36.sp,
                      fontWeight: FontWeight.bold,
                      color: Theme.of(context).textTheme.subtitle2.color),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 49.h, left: 37.w),
                child: tabShow("性别", data.sexual == '1' ? '男' : '女'),
              ),
              Padding(
                padding: EdgeInsets.only(top: 59.h, left: 37.w),
                child: tabShow("城市", data.city),
              ),
              Padding(
                padding: EdgeInsets.only(top: 59.h, left: 37.w),
                child: tabShow("公司", data.company),
              ),
              Padding(
                padding: EdgeInsets.only(top: 59.h, left: 37.w),
                child: tabShow("职位", data.position),
              ),
              Padding(
                padding: EdgeInsets.only(top: 59.h, left: 37.w),
                child: tabShow("邮箱", data.email),
              ),
              Padding(
                padding: EdgeInsets.only(top: 59.h, left: 37.w),
                child: tabShow("签名", data.sign),
              ),
            ],
          );
        } else {
          return Constants.empty;
        }
      },
    );
  }

  Widget tabShow(String title, String content) {
    return Row(
      children: <Widget>[
        Expanded(
          child: Text(
            title,
            style: TextStyle(
              fontSize: 32.sp,
              color: Color(0xFF999999),
            ),
          ),
          flex: 1,
        ),
        Expanded(
          child: Text(
            content == null || content.trim() == '' ? "未填写" : content,
            style: TextStyle(
              fontSize: 32.sp,
              color: Colors.black,
            ),
          ),
          flex: 3,
        )
      ],
    );
  }
}
